package com.crazypos.security.filter;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.BeforeFilter;
import com.crazypos.common.utils.JWTTokenUtil;
import com.crazypos.config.JWTConfig;
import com.crazypos.pojo.UserEntity;
import com.crazypos.security.entity.UserDetailEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class JWTAuthenticationTokenFilter extends BasicAuthenticationFilter {
    public JWTAuthenticationTokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取请求头中的token
        String headerToken = request.getHeader(JWTConfig.tokenHeader);

        if (headerToken != null && headerToken.startsWith(JWTConfig.tokenPrefix)) {
            try {
                // 截取JWT前缀
                String token = headerToken.replace(JWTConfig.tokenPrefix, "");

                // 解析JWT
//                UserDetailEntity userEntity = (UserDetailEntity) JWTTokenUtil.parseUserInfoFromToken(token, UserDetailEntity.class);
                Claims claims = JWTTokenUtil.parseToken(token).getBody();
                UserDetailEntity userEntity = JSON.parseObject(claims.get(JWTConfig.userTokenKey).toString(), UserDetailEntity.class);

                String userId = userEntity.getId();
                if (!StringUtils.isEmpty(userId)) {
                    // 获取角色
                    List<GrantedAuthority> authorities = new ArrayList<>();
                    String authority = claims.get("authorities").toString();

                    if (!StringUtils.isEmpty(authority)) {
                        List<Map<String, String>> authorityMap = JSONObject.parseObject(authority, List.class);
                        for(Map<String,String> role : authorityMap){
                            if(role != null) {
                                authorities.add(new SimpleGrantedAuthority(role.get("authority")));
                            }
                        }
                    }

                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEntity, userId, authorities);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }

            } catch (ExpiredJwtException ex) {
                log.info("jwt过期");
            } catch (Exception e) {
                log.info("Token无效");
            }
        }

        chain.doFilter(request, response);
        return;
    }
}
